package gatperdut.chato.core.interpreter.actions;

import gatperdut.chato.constants.CSConstantsCommandResult.CommandExecutionResult;
import gatperdut.chato.core.characters.BaseController;
import gatperdut.chato.core.interpreter.actions.generic.ItemTransferAction;
import gatperdut.chato.core.interpreter.grammar.comminfo.ItemTransferInfo;
import gatperdut.chato.core.item.ItemController;

public class GetFromRoomAction extends ItemTransferAction {

    public GetFromRoomAction( ItemTransferInfo info, BaseController entityController ) {
        super( info, entityController );
    }

    @Override
    public CommandExecutionResult perform() {
        checkForRunningCraft();

        if ( emptyEmote() ) {
            getEntityController().tx( "Empty emotes are not allowed." );
            return CommandExecutionResult.OK;
        }

        String emote = getLastPartEmote();
        if ( emote == null ) {
            getEntityController().tx( "Check your emote." );
            return CommandExecutionResult.OK;
        }

        synchronized ( getEntityController().getRoomController().getInventoryController() ) {
            ItemController ic = getEntityController().getRoomController().getInventoryController().getItemController( getInfo().getWhat() );
            if ( ic == null ) {
                getEntityController().tx( "You cannot find that." );
                return CommandExecutionResult.OK;
            }
            synchronized ( getEntityController().getInventoryController() ) {
                if ( !getEntityController().getInventoryController().hasOneFreeHand() ) {
                    getEntityController().tx( "You'll need at least a free hand to do that." );
                    return CommandExecutionResult.OK;
                }

                getEntityController().getRoomController().getInventoryController().takeFromInventory( ic );
            }

            getEntityController().getInventoryController().take( ic );
            getEntityController().getEchoes().txGetFromRoom( ic, emote );
        }

        return CommandExecutionResult.OK;
    }
}
